//
//  AuditQuestionViewController.m
//  auditorias
//
//  Created by Mauro on 7/28/13.
//  Copyright (c) 2013 Antilope. All rights reserved.
//

#import "AuditQuestionViewController.h"
#import "KeyboardManager.h"
#import "MBProgressHUD.h"
#import "DataLoader.h"
#import "SharedMemory.h"
#import "UIPlaceHolderTextView.h"
#import "AuditType.h"
#import "PointOfSell.h"
#import "ControlVariables.h"
#import "Audit.h"
#import "User.h"
#import "UKImage.h"
#import <math.h>


@interface AuditQuestionViewController ()

@end

@implementation AuditQuestionViewController

@synthesize mailTf;
@synthesize doButton;
@synthesize backgroundButton;
@synthesize scrollView;
@synthesize keyboardManager;
@synthesize uniqueId;
@synthesize pointOfSell;
@synthesize auditType;
@synthesize questionAnswer;
@synthesize photoPaths;


- (void) dealloc
{
    [mailTf release], mailTf = nil ;
    [doButton release], doButton = nil;
    [backgroundButton release], backgroundButton = nil;
    [scrollView release], scrollView = nil;
    [keyboardManager release], keyboardManager = nil;
    [uniqueId release], uniqueId = nil;
    [pointOfSell release], pointOfSell = nil;
    [auditType release], auditType = nil;
    [photoPaths release], photoPaths = nil;
    [_topBarView release];
    [super dealloc];
}

- (void)viewDidUnload
{
    self.mailTf = nil;
    self.doButton = nil;
    self.backgroundButton = nil;
    self.scrollView = nil;
    self.keyboardManager = nil;
    self.uniqueId = nil;
    self.pointOfSell = nil;
    self.auditType = nil;
    self.photoPaths = nil;
    [self deletePhotoAlbum];
    [super viewDidUnload];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [TopBarViewController setTitleLabelOf:_topBarView text:kTopBarTitleAuditQuestion];
    SharedMemory *mem = [SharedMemory sharedInstance];
    
    [SharedMemory createDirectory:PHOTO_DIRECTORY];
    
    self.questionAnswer = true;
    self.photoPaths = [[[NSMutableArray alloc] initWithObjects:@"",@"",@"", nil] autorelease];
    
    self.pointOfSell = [mem getPointOfSell];
    self.auditType = [mem getAuditType];
    
    UILabel *titleLabel = (UILabel *)[self.view viewWithTag:30];
    [titleLabel setText:self.auditType.name];
    
    UIView* layoutQuestion = (UIView*)[self.view viewWithTag:31];
    UIView* layoutPhotos = (UIView*)[self.view viewWithTag:32];
    if (self.auditType.isQuestionAudit) {
        UILabel* question =  (UILabel*)[layoutQuestion viewWithTag:42];
        [question setText:auditType.question];
    }
    else{
        int diff = (self.mailTf.frame.origin.y - layoutPhotos.frame.origin.y) ;
        layoutPhotos.frame = CGRectMake(layoutPhotos.frame.origin.x, layoutQuestion.frame.origin.y, layoutPhotos.frame.size.width, layoutPhotos.frame.size.height);
        self.mailTf.frame = CGRectMake(self.mailTf.frame.origin.x, diff + layoutPhotos.frame.origin.y, self.mailTf.frame.size.width, self.mailTf.frame.size.height + layoutQuestion.frame.size.height);
        layoutQuestion.hidden = true;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.keyboardManager = nil;
    [super viewWillDisappear:animated];
}

- (void)viewWillAppear:(BOOL)animated
{
    //[self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];
    
    self.keyboardManager = [[[KeyboardManager alloc] initWithDelegate:self.backgroundButton scrollView:self.scrollView elevation:70] autorelease];
    [self.mailTf setPlaceholder:@"Dejar un comentario..."];
    [self.mailTf setPlaceholderColor:[UIColor lightGrayColor]];
    //make contentSize bigger than your scrollSize (you will need to figure out for your own use case)
    CGSize scrollContentSize = CGSizeMake(320, 345);
    self.scrollView.contentSize = scrollContentSize;
}

- (IBAction)questionRadioButtonTapped:(id)sender
{
    [self backgroundTapped:sender];
    UIView* layoutQuestion = (UIView*)[self.view viewWithTag:31];
    UIButton* radioButtonYes = (UIButton*)[layoutQuestion viewWithTag:40];
    UIButton* radioButtonNo = (UIButton*)[layoutQuestion viewWithTag:41];
    radioButtonYes.selected = ((UIButton*)sender).tag == radioButtonYes.tag;
    radioButtonNo.selected = !radioButtonYes.selected;
    self.questionAnswer = radioButtonYes.selected;
    
}

- (IBAction)infoButtonTapped:(id)sender
{
    [self backgroundTapped:sender];
    [SharedMemory showError:@"Descripción:" andText:self.auditType.description];
}

- (IBAction)cancelButtonTapped:(id)sender
{
    [self backgroundTapped:sender];
    [self deletePhotoAlbum];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)confirmButtonTapped:(id)sender
{
    SharedMemory *mem = [SharedMemory sharedInstance];
    [self backgroundTapped:sender];
    bool isPhotoTaken = false;
    int i = 0;
    while(!isPhotoTaken && i< [self.photoPaths count]){
        isPhotoTaken = ! [((NSString*)[self.photoPaths objectAtIndex:i])isEqualToString:@""];
        i++;
    }
    if(!isPhotoTaken && self.questionAnswer==YES && self.auditType.requiresPhoto){
        [SharedMemory showError:@"" andText:auditquestion_must_photo];
        return;
    }
    
    //If needed the point of sell must be created
    if([self.pointOfSell.externalId isEqualToString:@""]){
        [SharedMemory createTextFile:[self.pointOfSell getFileName] data: [self.pointOfSell toInternalJSON] ];
    }
    
    Audit* audit = [[Audit alloc] initWithuniqueId:self.uniqueId
                                            userId:[mem getUser].externalId
                                     pointOfSellId:self.pointOfSell.externalId
                             pointOfSellInternalId:self.pointOfSell.internalId
                                       commentText:self.mailTf.text
                                       hasQuestion:self.auditType.isQuestionAudit
                                    questionAnswer:self.questionAnswer
                                       auditTypeId:self.auditType.externalId
                                        photoPaths:self.photoPaths];
    NSString* auditFileName = [audit getFileName];
    [SharedMemory createTextFile:auditFileName data: [audit toInternalJSON] ];
    [audit release];
    
    [self deletePhotoAlbum];
    //To mark the AuditTypes done
    NSString* nowString = [NSString stringWithFormat:@"%f",([self.uniqueId doubleValue]/1000.0)];
    [mem rememberStringOn:UNSYNC_AUDITS_KEY key:[mem makeOwnPDVnTypeId] value:nowString];
    [mem rememberStringOn:ONEMONTH_AUDITS_KEY key:[mem makeOwnPDVnTypeId] value:nowString];
    [mem rememberStringOn:ONEMONTH_PDVS_KEY key:[mem makeOwnPDVnId] value:self.uniqueId];
    [mem.auditTypesDone setObject:[NSNumber numberWithBool:true] atIndexedSubscript:mem.auditTypeIndex];
    mem.auditTypeIndex = -1;
    //To mark the PDVs done
    if(pointOfSell.statusType==PDV_TYPE_NONE)
        pointOfSell.statusType = PDV_TYPE_PENDING;
    
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - Keyboard hiding


- (IBAction)backgroundTapped:(id)sender
{
	[self.mailTf resignFirstResponder];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}


#pragma mark - Camera control

static int currentPhotoButtonTag = -1;

- (IBAction)photoButtonTapped:(id)sender
{
    [self backgroundTapped:sender];
    currentPhotoButtonTag = ((UIButton*)sender).tag;
    if([self startCameraControllerFromViewController: self usingDelegate: self] == NO){
        [SharedMemory showError:@"" andText:auditquestion_no_cammera];
    }
}


- (BOOL) startCameraControllerFromViewController: (UIViewController*) controller usingDelegate: (id <UIImagePickerControllerDelegate, UINavigationControllerDelegate>) delegate
{    
    if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera] == NO) || (delegate == nil)|| (controller == nil))
        return NO;
    
    UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init];
    cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    cameraUI.mediaTypes = [[[NSArray alloc] initWithObjects: (NSString *) kUTTypeImage, nil] autorelease];
    cameraUI.allowsEditing = NO;
    
    cameraUI.delegate = delegate;
    
    [controller presentViewController:cameraUI animated:YES completion:nil];
    return YES;
}

// For responding to the user tapping Cancel.
- (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker {
    
    //[[picker parentViewController] dismissModalViewControllerAnimated: YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
    [picker release];
}

// For responding to the user accepting a newly-captured picture or movie
- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info {
    
    UIImage *originalImage, *editedImage, *imageToSave;
    
    editedImage = (UIImage *) [info objectForKey: UIImagePickerControllerEditedImage];
    originalImage = (UIImage *) [info objectForKey: UIImagePickerControllerOriginalImage];
    
    if (editedImage) {
        imageToSave = editedImage;
    } else {
        //imageToSave = [originalImage rotate:UIImageOrientationRight];;
        imageToSave = originalImage;
    }
    
    // Save the new image (original or edited) to the Camera Roll
    //UIImageWriteToSavedPhotosAlbum (imageToSave, nil, nil , nil);
    [self saveImage:imageToSave];
    
    UIButton* photoButton  = (UIButton*)[self.view viewWithTag:currentPhotoButtonTag];
    [photoButton setImage:imageToSave forState:UIControlStateNormal];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    [picker release];
}

- (void)saveImage: (UIImage*)image
{
    if (image != nil)
    {
        SharedMemory* mem = [SharedMemory sharedInstance];
        int _index = currentPhotoButtonTag-50;
        NSString* fileName = [self makeFileNameForIndex:_index];
        NSString *documentsDirectory = [mem.documentsPath stringByAppendingPathComponent:PHOTO_DIRECTORY];
        NSString *filePath = [documentsDirectory  stringByAppendingPathComponent:fileName];
        //Image resize
        double scale = fmax(image.size.width, image.size.height) / IMAGE_MAX_SIZE;
        UIImage* newImage = image;
        if (scale>1.0) {
            CGSize newSize = CGSizeMake(image.size.width/scale, image.size.height/scale);
            UIGraphicsBeginImageContext(newSize);
            [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
            newImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        //Image compress and data version of it
        NSData* data = UIImageJPEGRepresentation(newImage,IMAGE_DEFAULT_COMPRESS_RATE);
        [data writeToFile:filePath atomically:YES];
        //data writeToFile:fileName options:(NSDataWritingOptions) error:NSError *error;
        //Sets the path in the array
        [self.photoPaths setObject:fileName atIndexedSubscript:_index];
        
        //TODO: borrar, es para ver el tamanyo del archivo
        //UIImageWriteToSavedPhotosAlbum (newImage, nil, nil , nil);
    }
}

-(NSString*)makeFileNameForIndex:(int)_index
{
    return [NSString stringWithFormat:@"%@%d_%@%@",PHOTO_PREFIX,_index,self.uniqueId,PHOTO_SUFIX];
}

- (bool) deletePhotoAlbum
{
    SharedMemory* mem = [SharedMemory sharedInstance];
    NSString *documentsDirectory = [mem.documentsPath stringByAppendingPathComponent:PHOTO_DIRECTORY];
    bool success =[[NSFileManager defaultManager] removeItemAtPath:documentsDirectory error:nil];
    return success;
}

@end
